package com.fin.zw.intelligentbot.service;

import com.fin.zw.intelligentbot.entity.Blacklist;
import com.fin.zw.intelligentbot.entity.QBlacklist;
import com.fin.zw.intelligentbot.model.session.SessionModel;
import com.fin.zw.intelligentbot.repository.BlacklistRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Optional;

@Service("blacklistService")
public class BlacklistService {

    @Autowired
    private BlacklistRepository blacklistRepository;

    /**
     * 黑名单添加
     *
     * @param phone
     * @param sessionModel
     */
    public void createBlacklist(String phone, SessionModel sessionModel) {
        Blacklist blacklist = new Blacklist();
        blacklist.setPhone(phone);
        blacklist.setCreateTime(new Date());
        blacklist.setCreateId(sessionModel.getId());
        blacklist.setCreateName(sessionModel.getUserName());
        blacklistRepository.save(blacklist);
    }

    /**
     * 黑名单删除
     *
     * @param phone
     */
    public void deleteBlacklistByPhone(String phone) {
        Optional<Blacklist> optional = blacklistRepository.findOne(QBlacklist.blacklist.phone.eq(phone));
        if (optional.isPresent()) {
            Blacklist blacklist = optional.get();
            blacklistRepository.delete(blacklist);
        }
    }

    /**
     * 黑名单删除
     *
     * @param id
     */
    public void deleteBlacklistById(String id) {
        blacklistRepository.deleteById(id);
    }

    /**
     * 黑名单查询
     *
     * @param pageable
     * @return
     */
    public Page<Blacklist> queryBlacklist(Pageable pageable) {
        Page<Blacklist> page = blacklistRepository.findAll(pageable);
        return page;
    }

    /**
     * 判断电话是否是黑名单
     *
     * @param phone
     * @return
     */
    public boolean exitBlackListByPhone(String phone) {
        Boolean result = false;
        if (StringUtils.isNotBlank(phone)) {
            Optional<Blacklist> optional = blacklistRepository.findOne(QBlacklist.blacklist.phone.eq(phone));
            if (optional.isPresent()) {
                result = true;
            }
        }
        return result;
    }
}
